<template>
    <!-- 饼状图 -->
    <div>
      <div class="query-wrap">
        <el-checkbox
          v-model="queryParams.qulityControl"
          label="品控关注"
          border
          size="small"
          class="related-me"
          true-label="Y"
          :false-label="null"
          @change='handleQuery'
        ></el-checkbox>
        <div class="button-wrap">
          <el-button :type="activeName == 1 ? 'primary' : ''" @click='changeTab("1")' size="mini">今日</el-button>
          <el-button :type="activeName == 2 ? 'primary' : ''" @click='changeTab("2")' size="mini" class="seven">近七日</el-button>
        </div>
      </div>

      <div class='chart-wrap'>
        <div
          ref="chartAbnormal"
          class="chart-content"
          style="{height: 200px;}"
        >
        </div>

        <div
          ref="chartWarn"
          class="chart-content"
          style="{height: 200px;}"
        >
        </div>
      </div>
    </div>
</template>
<script>
  import {statusMapList} from "../../exceptionMgmt/enum.js"
  import {coreFocusAbnormal,coreFocusWarn} from "@/api/workbench";
  import equipList from "@/views/components/equipList";
  import { getMaterialConsumeOption,getAbnomalOption,getWarnOption } from '../echartOption'
  import { mapState,mapMutations} from "vuex";
export default {
  props:{
    lindCodes:{
      type:String,
      default:""
    },
    filterData:{
      type:Object,
      default:()=>{}
    }
  },
  data() {
    return {
      queryParams:{
        erpProductionLineCodes:[],
        todayOrWeek:"1",
        qulityControl:null
      },
      activeName:"1",
      loading: false,
      echartsWarnInstance: null,
      echartsAbnormalInstance: null,
      warnTotal:0,
      abnormalTotal:0,
      rateComplete:0,
      chartWarnData:[],
      chartAbnormalData:[],
      refreshTimer:null,
      statusMapList
    };
  },
  // created(){
  //   this.getWarnList();
  //   this.getAbnormalList()
  // },

  methods:{
    ...mapMutations("workbench", ["SET_ABNORMAL_DETAIL","SET_ABNORMAL_HIS_DETAIL","SET_WARN_DETAIL"]),
    setRefreshTimer(){
      if (this.refreshTimer) {
        if(this.echartsWarnInstance){
          this.echartsWarnInstance.off('legendselectchanged')
        }
        if(this.echartsAbnormalInstance){
          this.echartsAbnormalInstance.off('legendselectchanged')
        }
        clearTimeout(this.refreshTimer);
      }
      this.refreshTimer = setTimeout(() => {
        this.getWarnList();
        this.getAbnormalList()
        this.setRefreshTimer();
      },60000)
    },

    getWarnList(){
      this.warnTotal = 0;
      let tableData = []
      coreFocusWarn(this.queryParams)
      .then((res) => {
        this.chartWarnData = [];
        if(res.code == 200 && res.data){
          tableData = res.data;
          this.$nextTick(()=>{
            this.chartWarnData.push(
              { value: tableData.warmEffect, name:'预警' },
              { value: tableData.warmCancel, name: '已失效' }
            )
            this.warnTotal = tableData.warmEffect + tableData.warmCancel
            this.initChart("warn")
          })
        }
        else{
          this.warnTotal = 0;
          tableData = [];
          this.chartWarnData = [];
        }
      })
      .catch(() => {
        this.warnTotal = 0;
        tableData = [];
        this.chartWarnData = [];
      });
    },

    getAbnormalList(){
      this.abnormalTotal = 0;
      this.rateComplete = 0;
      let tableData = []
      coreFocusAbnormal(this.queryParams)
      .then((res) => {
        this.chartAbnormalData = [];
        if(res.code == 200 && res.data){
          tableData = res.data;
          this.$nextTick(()=>{
            this.chartAbnormalData.push(
              { value: tableData.abnormalHandle, name:'待处理' },
              { value: tableData.abnormalProgress, name: '进行中' },
              { value: tableData.abnormalIgnore, name: '已忽略' },
              { value: tableData.abnormalComplate, name: '已完成' },
              { value: tableData.abnormalClose, name: '已关闭' }
            )
            this.chartAbnormalData.forEach(item => {
              this.abnormalTotal += item.value
            })
            if(this.abnormalTotal){
              this.rateComplete = ((tableData.abnormalComplate/this.abnormalTotal)*100).toFixed(2) > 0 ? ((tableData.abnormalComplate/this.abnormalTotal)*100).toFixed(2)+'%': 0
            }
            this.initChart("abnormal")
          })
        }
        else{
          this.abnormalTotal = 0;
          this.rateComplete = 0;
          tableData = []
          this.chartAbnormalData = []
        }
      })
      .catch(() => {
        this.abnormalTotal = 0;
        this.rateComplete = 0;
        tableData = []
        this.chartAbnormalData = []
      });
    },

    changeTab(tab){
      this.activeName = tab;
      this.queryParams.todayOrWeek = tab;
      this.getWarnList();
      this.getAbnormalList();
    },

    handleQuery() {
      this.getWarnList();
      this.getAbnormalList();
    },

    initChart(type){
      if(type == "abnormal"){
        this.echartsAbnormalInstance = null;
        this.echartsAbnormalInstance = this.$echarts.init(this.$refs.chartAbnormal, null, {renderer:'svg'})
        const abnormalOption = getAbnomalOption(this.chartAbnormalData,this.abnormalTotal,this.rateComplete)
        this.echartsAbnormalInstance.setOption(abnormalOption)
        if(this.echartsAbnormalInstance){
          this.echartsAbnormalInstance.off('legendselectchanged')
        }
        this.echartsAbnormalInstance.on('legendselectchanged', (params)=> this.queryData(params,type))
      }
      else if(type == "warn"){
        this.echartsWarnInstance = null;
        this.echartsWarnInstance = this.$echarts.init(this.$refs.chartWarn, null, {renderer:'svg'})
        const warnOption = getWarnOption(this.chartWarnData,this.warnTotal)
        this.echartsWarnInstance.setOption(warnOption)
        if(this.echartsWarnInstance){
          this.echartsWarnInstance.off('legendselectchanged')
        }
        this.echartsWarnInstance.on('legendselectchanged', (params)=> this.queryData(params,type))
      }
    },

    queryData(params,type){
      const {ownedFactory,ownedWorkshop,ownedProductionLine,lineId} = this.filterData;
      let time = [];
      if(this.activeName == "1"){//今日
        time = this.toTeamTimeSep(1);
      }else{
        time = this.toTeamTimeSep(7);
      }
      let path ="./"
      if(type == "abnormal"){//异常
        const status = this.statusMapList?.length && this.statusMapList.find(ele => ele.label === params.name)?.value
        if(status == "1" || status == "2"){//待处理，进行中
          this.SET_ABNORMAL_DETAIL({
            factoryDeptCode:ownedFactory,
            workshopCode:ownedWorkshop,
            erpProductionLineCode:ownedProductionLine,
            lineId,
            relatedVsMe:false,
            qulityControl:this.queryParams.qulityControl,
            status,
            start:time[0],
            end:time[1]
          });
          path = "/exceptionMgmt/operate"
        }
        else if(status == "3" || status == "4" || status == "5"){//已完成，已关闭，已忽略
          this.SET_ABNORMAL_HIS_DETAIL({
            factoryDeptCode:ownedFactory,
            workshopCode:ownedWorkshop,
            erpProductionLineCode:ownedProductionLine,
            lineId,
            relatedVsMe:false,
            qulityControl:this.queryParams.qulityControl,
            status,
            start:time[0],
            end:time[1]
          })
          path = "/exceptionMgmt/history"
        }
      }else{
        this.SET_WARN_DETAIL({
          factoryDeptCode:ownedFactory,
          workshopCode:ownedWorkshop,
          erpProductionLineCode:ownedProductionLine,
          lineId,
          relatedVsMe:false,
          qulityControl:this.queryParams.qulityControl,
          start:time[0],
          end:time[1]
        })
        path = "/exceptionMgmt/warning"
      }
      this.$router.push({ path: path})
      .catch(()=>{});
    },

    resize() {
      this.echartsWarnInstance?.resize()
      this.echartsAbnormalInstance?.resize()
    },

    resetOption(){
      // 指定图表的配置项和数据
      const warnOption = getWarnOption(this.chartWarnData)
      const abnormalOption = getAbnomalOption(this.chartAbnormalData)

      // 使用刚指定的配置项和数据显示图表。
      if (!this.echartsWarnInstance && !this.echartsAbnormalInstance) {
        return
      }
      if (!this.echartsAbnormalInstance && !this.echartsAbnormalInstance) {
        return
      }
      this.echartsWarnInstance.setOption(warnOption)
      this.echartsAbnormalInstance.setOption(abnormalOption)
      const timer = setTimeout(() => {
        clearTimeout(timer)
        this.resize()
      }, 100);
    }
  },
  watch:{
    lindCodes:{
      handler(newVal){
        if(newVal){
          this.queryParams.erpProductionLineCodes = newVal.split(",");
        }
        // 清除轮询
        if (this.refreshTimer) {
          if(this.echartsWarnInstance){
            this.echartsWarnInstance.off('legendselectchanged')
          }
          if(this.echartsAbnormalInstance){
            this.echartsAbnormalInstance.off('legendselectchanged')
          }
          clearTimeout(this.refreshTimer);
        }
        this.getWarnList();
        this.getAbnormalList()
        this.setRefreshTimer()
      },
      deep: true,
      immediate: true
    }
  },
  beforeDestroy(){
    if (this.refreshTimer) {
      if(this.echartsWarnInstance){
        this.echartsWarnInstance.off('legendselectchanged')
      }
      if(this.echartsAbnormalInstance){
        this.echartsAbnormalInstance.off('legendselectchanged')
      }
      clearTimeout(this.refreshTimer);
    }
  },
  destroyed(){
    if (this.refreshTimer) {
      if(this.echartsWarnInstance){
        this.echartsWarnInstance.off('legendselectchanged')
      }
      if(this.echartsAbnormalInstance){
        this.echartsAbnormalInstance.off('legendselectchanged')
      }
      clearTimeout(this.refreshTimer);
    }
  }
};
</script>
<style lang="scss" scoped>
  .chart-wrap{
    width: 100%;
    height: 300px;
    display: flex;
    align-items: center;
    justify-content:space-between;
    .chart-content{
      width: 49%;
      height: 100%;
    }
  }
  .query-wrap{
    display: flex;
    align-items: flex-start;
    justify-content:flex-end;
    .button-wrap{
      margin-left:16px;
      text-align:right
    }
    .seven{
      margin-left:4px;
    }
  }
</style>
